﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace CPPEI.Coolzon.UI.DataPartLib
{
    /// <summary>
    /// Interaction logic for DataTextAnimationLabel2.xaml
    /// </summary>
    [XPartIcon("pack://application:,,,/CPPEI.Coolzon.UI.DataPartLib;component/Images/PartIcons/文字动画标签2.png")]
    [System.ComponentModel.DisplayName("文本动画标签2")]
    public partial class DataTextAnimationLabel2 : DataAnimationLabelBase
    {
        private Storyboard _animationStoryboard;

        public DataTextAnimationLabel2()
        {
            XText = "文本动画标签2";
            XAnimationDirection = "down";
            InitializeComponent();
        }

        #region Constructor

        protected override void OnActive(PartContext context)
        {
            base.OnActive(context);
            if (!string.IsNullOrWhiteSpace(XText))
            {
                TextAnimation(XText);
            }
        }
        protected override void OnDeactive(PartContext context)
        {
            OnDestory();
        }
        protected override void OnDestory()
        {
            if (_animationStoryboard != null)
            {
                _animationStoryboard.Stop();
                _animationStoryboard.Remove();
                _animationStoryboard = null;
            }
            gdLayout.Children.Clear();
            base.OnDestory();
        }
        protected override void OnDataItemBinding(ServiceProxy.DataServiceRef.DataItem dataItem)
        {
            StopAnimation();
            XText = dataItem.Value;
        }

        protected override void OnApplyXProperty()
        {
            base.OnApplyXProperty();
            if (!string.IsNullOrWhiteSpace(XText))
            {
                TextAnimation(XText);
            }
        }

        private void TextAnimation(string xText)
        {
            if(double.IsNaN(Height) || double.IsNaN(Width) || string.IsNullOrWhiteSpace(XAnimationDirection))
            {
                return;
            }
            ClearAnimation();
            StopAnimation();
            _animationStoryboard = new Storyboard();
            _animationStoryboard.FillBehavior = FillBehavior.HoldEnd;
            _animationStoryboard.Completed += _animationStoryboard_Completed;

            gdLayout.Children.Clear();

            string itemValueString = xText;

            double everyWidth = GetEveryCharWeight(itemValueString.Length);

            int startIndex = 0, endIndex = itemValueString.Length, offset = 1;
            StackPanel sp = new StackPanel();
            sp.Orientation = Orientation.Horizontal;
            if (XFlowDirection != null && XFlowDirection.Equals("RightToLeft", StringComparison.OrdinalIgnoreCase))
            {
                sp.FlowDirection = FlowDirection.RightToLeft;
                startIndex = itemValueString.Length - 1;
                endIndex = -1;
                offset = -1;
            }
            sp.Width = Width;
            for (int i = startIndex; i != endIndex; i = i + offset)
            {
                char digital = itemValueString[i];
                Grid gridShadow = new Grid();
                ImageBrush imageBrush = new ImageBrush(XDigitalImage == null ? null : XDigitalImage.ImageSource);
                imageBrush.Stretch = Stretch.Fill;
                gridShadow.Background = imageBrush;
                for (int shadowIndex = 1; shadowIndex <= 3; shadowIndex++)
                {
                    Label lb = new Label();
                    lb.Height = Height;
                    lb.Width = everyWidth;
                    lb.Margin = XLabelMargin;
                    lb.ClipToBounds = true;
                    lb.Effect = GetDropShadowEffect();
                    InitControl(lb);
                    lb.Content = digital.ToString();

                    gridShadow.Children.Add(lb);
                }

                sp.Children.Add(gridShadow);
            }
            gdLayout.Children.Add(sp);

            double beginLeft = 0, endLeft = 0, beginTop = 0, endTop = 0;
            if (XAnimationDirection.ToUpper().Equals("UP"))
            {
                beginTop = Height * -1;
            }
            else if (XAnimationDirection.ToUpper().Equals("DOWN"))
            {
                beginTop = Height;
            }
            else if (XAnimationDirection.ToUpper().Equals("LEFT"))
            {
                beginLeft = Width * -1;
            }
            else if (XAnimationDirection.ToUpper().Equals("RIGHT"))
            {
                beginLeft = Width;
            }

            DoubleAnimation leftAnimation = new DoubleAnimation(beginLeft, endLeft, new Duration(TimeSpan.FromSeconds(XDataAnimationDuration)));
            Storyboard.SetTarget(leftAnimation, gdLayout);
            Storyboard.SetTargetProperty(leftAnimation, new PropertyPath(Canvas.LeftProperty));
            _animationStoryboard.Children.Add(leftAnimation);

            DoubleAnimation topAnimation = new DoubleAnimation(beginTop, endTop, new Duration(TimeSpan.FromSeconds(XDataAnimationDuration)));
            Storyboard.SetTarget(topAnimation, gdLayout);
            Storyboard.SetTargetProperty(topAnimation, new PropertyPath(Canvas.TopProperty));
            _animationStoryboard.Children.Add(topAnimation);

            if (_animationStoryboard != null)
            {
                _animationStoryboard.Begin();
            }
        }


        /// <summary>
        /// 初始化控件属性
        /// </summary>
        private void InitControl(Label lb)
        {
            if (XFontSize != 0)
            {
                lb.FontSize = XFontSize;
            }
            lb.HorizontalContentAlignment = XTextAlign;
            lb.VerticalContentAlignment = XTextVAlign;
            if (XFont != null)
            {
                lb.FontFamily = XFont;
            }
            lb.FontWeight = XFontWeight;
            if (XForeground != null)
            {
                lb.Foreground = XForeground.Brush;
            }
            lb.Height = Height;
        }
        #endregion

        /// <summary>
        /// 动画完成事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void _animationStoryboard_Completed(object sender, EventArgs e)
        {
            ClearAnimation();
        }
        /// <summary>
        /// 清理动画，清理故事版中每个动画的target，防止内存溢出
        /// </summary>
        private void ClearAnimation()
        {
            if (_animationStoryboard != null)
            {
                foreach (Timeline tl in _animationStoryboard.Children)
                {
                    tl.ClearValue(Storyboard.TargetProperty);
                }
            }
        }
        private void StopAnimation()
        {
            if (_animationStoryboard != null)
            {
                _animationStoryboard.Completed -= _animationStoryboard_Completed;
                _animationStoryboard.Stop();
                _animationStoryboard.Remove();
                _animationStoryboard = null;
            }
        }
    }
}
